package com.lw.lost.daos

import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase

class FriendRequestDao(private val db: SQLiteDatabase) {
    
    fun sendRequest(senderId: Long, receiverId: Long, message: String): Long {
        val values = ContentValues().apply {
            put("senderId", senderId)
            put("receiverId", receiverId)
            put("message", message)
            put("status", 0)
        }
        return db.insert("friend_requests", null, values)
    }

    fun getRequestsByReceiverId(receiverId: Long): Cursor {
        return db.rawQuery("""
            SELECT 
                fr.*,
                u.name as senderName,
                u.avatar as senderAvatar
            FROM friend_requests fr
            LEFT JOIN users u ON fr.senderId = u.userId
            WHERE fr.receiverId = ? AND fr.status = 0
            ORDER BY fr.createTime DESC
        """, arrayOf(receiverId.toString()))
    }

    fun updateRequestStatus(requestId: Long, status: Int): Int {
        val values = ContentValues().apply {
            put("status", status)
        }
        return db.update(
            "friend_requests",
            values,
            "requestId = ?",
            arrayOf(requestId.toString())
        )
    }

    fun hasUnhandledRequest(senderId: Long, receiverId: Long): Boolean {
        return db.query(
            "friend_requests",
            null,
            "senderId = ? AND receiverId = ? AND status = 0",
            arrayOf(senderId.toString(), receiverId.toString()),
            null,
            null,
            null
        ).use { cursor ->
            cursor.count > 0
        }
    }
} 